package com.example.app_mqttclient.obj;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.app_mqttclient.MainActivity;
import com.example.app_mqttclient.broadcast.MyBroadcast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.Serializable;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MyMqttClient {
    private static final String TAG = "MyMqttClient";
    // mqtt服务器IP地址和端口号
    private static String host = "tcp://39.105.62.98:1883";
    // 登录账号
    private static String userName = "admin";
    // 登录密码
    private static String password = "123";
    // 客户端唯一ID
    private static String clientID = "mqtt123";
    // 订阅主题 设备发送的
    private static String subscribeTopic = null;
    // 发布主题 设备接收的
    private static String publishTopic = null;
    // 回调处理函数
    private static Handler handler;
    // 客户端
    private static MqttClient client = null;
    // Mqtt连接设置
    private static MqttConnectOptions options;
    //
    private static ScheduledExecutorService scheduler;


    public MyMqttClient(String host_l, String port_l) {
        host = "tcp://" + host_l + ":" + port_l;
        Log.i(TAG, "MQTT client host: " + host);
    }

    public static void beginMqttClient()
    {
        mqttInit();
        mqttStartReconnect();
        handler = new Handler() {

            @SuppressLint("SetTextIl8n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1: //开机校验更新回传
                        break;
                    case 2: //反馈回转
                        break;
                    case 3: //MQTT收到消息回传
//                        tv_msg.setText(msg.obj.toString());
                        break;
                    case 30: //连接失败
//                        Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                        break;
                    case 31: //连接成功
                        Log.i(TAG, "mqtt connect success!");

                        break;
                    default:
                        break;
                }
            }
        };
    }

    /**
     * 初始化MQTT配制
     */
    private static void mqttInit() {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, clientID, new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(password.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*40秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(40);
            //设置回调
            client.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    Log.i(TAG, "connectionLost");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    Log.i(TAG, "deliveryComplete: " + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message) throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    Message msg = new Message();
                    msg.what = 3;
                    //重新编码，解决乱码问题
                    String strMsg = new String(message.getPayload(), "GB2312");
                    int index = 0;
                    for(index = 0; index < MainActivity.deviceData.size(); index++)
                    {
                        // 检索收到的topic在deviceViewList中的位置
                        if(MainActivity.deviceData.get(index).getDevicePubTopic().equals(topicName))
                        {
                            Intent intent = new Intent("com.example.app_mqttclient.MQTT_RECV_DATA");
                            intent.putExtra("deviceIndex", index);
                            intent.putExtra("msg", strMsg);
                            MainActivity.localBroadcastManager.sendBroadcast(intent);

                            break;
                        }
                    }

                    handler.sendMessage(msg);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接
     */
    private static void mqttConnect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!(client.isConnected())) {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    /**
     * 线程池执行任务，心跳包，当断开连接后，执行自动连接代理服务器
     */
    private static void mqttStartReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!(client.isConnected())) {
                    mqttConnect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    /**
     * 发布订阅
     *
     * @param pub_topic_l
     * @param msg_l
     */
    public static void mqttPublish(String pub_topic_l, String msg_l) {
        if (client == null || !(client.isConnected())) {
            return;
        }
        MqttMessage msg = new MqttMessage();
        msg.setPayload(msg_l.getBytes());
        try {
            client.publish(pub_topic_l, msg);
            Log.i(TAG, "mqttPublish---" + pub_topic_l + ":" + msg);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static void mqttSubscribe(String sub_topic_l, int qos_l) {
        if (sub_topic_l == null || !(client.isConnected())) {
            return;
        }
        try {
            client.subscribe(sub_topic_l, qos_l);
            Log.i(TAG, "mqttSubscribe---" + sub_topic_l + ":" + qos_l);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}
